package com.ahdy.controller;

import com.ahdy.entity.DailyMedicationTask;
import com.ahdy.service.DailyMedicationTaskService;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 每日用药任务管理控制器
 */
@RestController
@RequestMapping("/api/daily-medication-tasks")
public class DailyMedicationTaskController {

    @Autowired
    private DailyMedicationTaskService dailyMedicationTaskService;

    /**
     * 添加每日用药任务
     *
     * @param task 每日用药任务实体
     * @return 响应结果
     */
    @PostMapping
    public ResponseEntity<Map<String, Object>> addDailyMedicationTask(@Valid @RequestBody DailyMedicationTask task) {
        Integer id = dailyMedicationTaskService.addDailyMedicationTask(task);
        Map<String, Object> response = new HashMap<>();
        response.put("code", 200);
        response.put("message", "添加每日用药任务成功");
        response.put("data", id);
        return ResponseEntity.status(HttpStatus.CREATED).body(response);
    }

    /**
     * 批量添加每日用药任务
     *
     * @param tasks 每日用药任务列表
     * @return 响应结果
     */
    @PostMapping("/batch")
    public ResponseEntity<Map<String, Object>> batchAddDailyMedicationTasks(
            @Valid @RequestBody List<DailyMedicationTask> tasks) {
        int rows = dailyMedicationTaskService.batchAddDailyMedicationTasks(tasks);
        Map<String, Object> response = new HashMap<>();
        response.put("code", 200);
        response.put("message", "批量添加每日用药任务成功");
        response.put("data", rows);
        return ResponseEntity.status(HttpStatus.CREATED).body(response);
    }

    /**
     * 更新任务状态
     *
     * @param id        任务ID
     * @param statusMap 状态参数
     * @return 响应结果
     */
    @PutMapping("/{id}/status")
    public ResponseEntity<Map<String, Object>> updateTaskStatus(
            @PathVariable Integer id,
            @RequestBody Map<String, String> statusMap) {

        DailyMedicationTask.TaskStatus status = DailyMedicationTask.TaskStatus.valueOf(statusMap.get("status"));
        int rows = dailyMedicationTaskService.updateTaskStatus(id, status);

        Map<String, Object> response = new HashMap<>();
        if (rows > 0) {
            response.put("code", 200);
            response.put("message", "更新任务状态成功");
        } else {
            response.put("code", 404);
            response.put("message", "任务不存在");
        }
        return ResponseEntity.ok(response);
    }

    /**
     * 删除每日用药任务
     *
     * @param id 任务ID
     * @return 响应结果
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<Map<String, Object>> deleteDailyMedicationTask(@PathVariable Integer id) {
        int rows = dailyMedicationTaskService.deleteDailyMedicationTask(id);

        Map<String, Object> response = new HashMap<>();
        if (rows > 0) {
            response.put("code", 200);
            response.put("message", "删除每日用药任务成功");
        } else {
            response.put("code", 404);
            response.put("message", "任务不存在");
        }
        return ResponseEntity.ok(response);
    }

    /**
     * 根据ID查询每日用药任务
     *
     * @param id 任务ID
     * @return 响应结果
     */
    @GetMapping("/{id}")
    public ResponseEntity<Map<String, Object>> getDailyMedicationTaskById(@PathVariable Integer id) {
        DailyMedicationTask task = dailyMedicationTaskService.getDailyMedicationTaskById(id);

        Map<String, Object> response = new HashMap<>();
        if (task != null) {
            response.put("code", 200);
            response.put("message", "获取每日用药任务成功");
            response.put("data", task);
            return ResponseEntity.ok(response);
        } else {
            response.put("code", 404);
            response.put("message", "任务不存在");
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(response);
        }
    }

    /**
     * 根据用户ID和日期查询每日用药任务列表
     *
     * @param userId 用户ID
     * @param date   任务日期
     * @return 响应结果
     */
    @GetMapping("/user/{userId}/date/{date}")
    public ResponseEntity<Map<String, Object>> getDailyMedicationTasksByUserIdAndDate(
            @PathVariable Integer userId,
            @PathVariable @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate date) {

        List<DailyMedicationTask> tasks = dailyMedicationTaskService.getDailyMedicationTasksByUserIdAndDate(userId,
                date);

        Map<String, Object> response = new HashMap<>();
        response.put("code", 200);
        response.put("message", "获取指定日期用药任务列表成功");
        response.put("data", tasks);
        return ResponseEntity.ok(response);
    }

    /**
     * 根据用户ID和日期范围查询每日用药任务列表
     *
     * @param userId    用户ID
     * @param startDate 开始日期
     * @param endDate   结束日期
     * @return 响应结果
     */
    @GetMapping("/user/{userId}/date-range")
    public ResponseEntity<Map<String, Object>> getDailyMedicationTasksByUserIdAndDateRange(
            @PathVariable Integer userId,
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate,
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate) {

        List<DailyMedicationTask> tasks = dailyMedicationTaskService.getDailyMedicationTasksByUserIdAndDateRange(userId,
                startDate, endDate);

        Map<String, Object> response = new HashMap<>();
        response.put("code", 200);
        response.put("message", "获取指定日期范围用药任务列表成功");
        response.put("data", tasks);
        return ResponseEntity.ok(response);
    }

    /**
     * 查询指定日期未完成的每日用药任务列表
     *
     * @param date 任务日期
     * @return 响应结果
     */
    @GetMapping("/uncompleted/{date}")
    public ResponseEntity<Map<String, Object>> getUncompletedTasksByDate(
            @PathVariable @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate date) {

        List<DailyMedicationTask> tasks = dailyMedicationTaskService.getUncompletedTasksByDate(date);

        Map<String, Object> response = new HashMap<>();
        response.put("code", 200);
        response.put("message", "获取指定日期未完成任务列表成功");
        response.put("data", tasks);
        return ResponseEntity.ok(response);
    }

    /**
     * 根据用户ID删除所有每日用药任务
     *
     * @param userId 用户ID
     * @return 响应结果
     */
    @DeleteMapping("/user/{userId}")
    public ResponseEntity<Map<String, Object>> deleteDailyMedicationTasksByUserId(@PathVariable Integer userId) {
        int rows = dailyMedicationTaskService.deleteDailyMedicationTasksByUserId(userId);

        Map<String, Object> response = new HashMap<>();
        response.put("code", 200);
        response.put("message", "删除用户所有用药任务成功");
        response.put("data", rows);
        return ResponseEntity.ok(response);
    }

    /**
     * 根据计划ID删除所有每日用药任务
     *
     * @param planId 计划ID
     * @return 响应结果
     */
    @DeleteMapping("/plan/{planId}")
    public ResponseEntity<Map<String, Object>> deleteDailyMedicationTasksByPlanId(@PathVariable Integer planId) {
        int rows = dailyMedicationTaskService.deleteDailyMedicationTasksByPlanId(planId);

        Map<String, Object> response = new HashMap<>();
        response.put("code", 200);
        response.put("message", "删除计划相关用药任务成功");
        response.put("data", rows);
        return ResponseEntity.ok(response);
    }

    /**
     * 获取今日用药任务统计
     *
     * @param userId 用户ID
     * @return 响应结果
     */
    @GetMapping("/statistics/today/{userId}")
    public ResponseEntity<Map<String, Object>> getTodayTaskStatistics(@PathVariable Integer userId) {
        Map<String, Object> statistics = dailyMedicationTaskService.getTodayTaskStatistics(userId);

        Map<String, Object> response = new HashMap<>();
        response.put("code", 200);
        response.put("message", "获取今日用药任务统计成功");
        response.put("data", statistics);
        return ResponseEntity.ok(response);
    }

    /**
     * 获取需要提醒的任务
     *
     * @param date        日期
     * @param currentTime 当前时间
     * @return 响应结果
     */
    @GetMapping("/reminder")
    public ResponseEntity<Map<String, Object>> getTasksNeedingReminder(
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate date,
            @RequestParam String currentTime) {

        List<DailyMedicationTask> tasks = dailyMedicationTaskService.getTasksNeedingReminder(date, currentTime);

        Map<String, Object> response = new HashMap<>();
        response.put("code", 200);
        response.put("message", "获取需要提醒的任务列表成功");
        response.put("data", tasks);
        return ResponseEntity.ok(response);
    }

    /**
     * 获取延迟服药任务（用于通知家属）
     *
     * @param date         日期
     * @param delayMinutes 延迟分钟数
     * @return 响应结果
     */
    @GetMapping("/delayed-notification")
    public ResponseEntity<Map<String, Object>> getDelayedTasksForNotification(
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate date,
            @RequestParam(defaultValue = "30") Integer delayMinutes) {

        List<Map<String, Object>> delayedTasks = dailyMedicationTaskService.getDelayedTasksForNotification(date,
                delayMinutes);

        Map<String, Object> response = new HashMap<>();
        response.put("code", 200);
        response.put("message", "获取延迟服药通知列表成功");
        response.put("data", delayedTasks);
        return ResponseEntity.ok(response);
    }
}
